package com.mukefile.dao.impl;

import com.mukefile.dao.UserDao;
import com.mukefile.pojo.MukeFile;
import com.mukefile.pojo.User;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: kenewstar
 * @Description: 数据访问层对象
 * @Date:Created in 2020/5/4
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Override
    public User selectUser(User user) {
        //获取Session
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        //Sql语句
        String sql = "select * from user where username=? and password=?";
        //创建查询
        Query query = session.createSQLQuery(sql).addEntity(User.class)
                .setParameter(1, user.getUsername())
                .setParameter(2, user.getPassword());
        //返回查询数据
        if (query.list().isEmpty()){
            return null;
        }else {
            return (User) query.list().get(0);
        }
    }

    @Override
    public int updateUserPassword(String pwd, User user) {
        user.setPassword(pwd);
        this.hibernateTemplate.update(user);

        return 1;
    }

    @Override
    public List<MukeFile> selectFileByLike(String fileName, User user) {
        //获取session
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        //Sql
        String sql = "select * from file where uid=? and filename like ?";
        //创建查询
        Query query = session.createSQLQuery(sql).addEntity(MukeFile.class)
                .setParameter(1,user.getId()).setParameter(2,"%"+fileName+"%");
        return query.list();
    }

    @Override
    public Integer selectUserIdByUsername(String username) {
        // 获取session
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        // Sql
        String sql = " SELECT * FROM `user` WHERE username=? ";
        List list = session.createSQLQuery(sql).addEntity(User.class)
                .setParameter(1,username).list();
        // 返回id
        return list.size()>0?((User)(list.get(0))).getId():null;
    }

    @Override
    public User selectUserById(Integer uid) {
        return this.hibernateTemplate.get(User.class, uid);
    }
}
